package com.huangd.platform.modules.sys.controller;

import cn.hutool.crypto.SecureUtil;
import com.huangd.platform.modules.sys.entity.TblUserEntity;
import com.huangd.platform.modules.sys.form.SysLoginForm;
import com.huangd.platform.modules.sys.service.SysCaptchaService;
import com.huangd.platform.modules.sys.service.SysUserTokenService;
import com.huangd.platform.modules.sys.service.TblUserService;
import com.huangd.platform.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 *
 * @author huangd
 */
@RestController
@Api(tags={"用户登录相关"})
public class SysLoginController extends AbstractController {
	@Resource
	private TblUserService sysUserService;
	@Resource
	private SysUserTokenService sysUserTokenService;
	@Resource
	private SysCaptchaService sysCaptchaService;

	@Value("${huangd.is-captcha}")
	private boolean isCaptcha;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@ApiOperation(value = "登录")
	@PostMapping("/sys/login")
	public R login(@RequestBody SysLoginForm form)throws IOException {
		System.out.println(isCaptcha);
		if (isCaptcha) {
			boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
			if(!captcha){
				return R.error("验证码不正确");
			}
		}

		//用户信息
		TblUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(SecureUtil.md5(form.getPassword()))) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() != 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getId());
		return r;
	}


	/**
	 * 退出
	 */
	@ApiOperation(value = "登出")
	@ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String")
	@PostMapping("/sys/logout")
	public R logout(String token) {
		sysUserTokenService.logout(token);
		return R.ok();
	}

}
